package com.dxh.sqlSession;

import com.dxh.pojo.Configuration;
import com.dxh.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

/**
 * @Description
 * @Date 2020-11-07 22:06
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        //将要完成对simpleExecutor里的query方法调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<Object> list = simpleExecutor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size()==1){
            return (T) objects.get(0);
        }else{
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }
    }

    @Override
    public Integer insert(String statementId, Object... params) throws Exception {
        return update(statementId, params);
    }

    @Override
    public Integer delete(String statementId, Object... params) throws Exception {
        return update(statementId, params);
    }

    @Override
    public Integer update(String statementId, Object... params) throws Exception {
        //将要完成对simpleExecutor里的query方法调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        Integer rowCount = simpleExecutor.update(configuration, configuration.getMappedStatementMap().get(statementId), params);
        return rowCount;
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用JDK动态代理来为Dao接口生成代理对象，并返回
        Object o = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(),
                new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层都还是执行JDBC代码  //根据不同情况 调用selectList或者selectOne
                //准备参数： 1. statementId
                /**
                 * **此时就有一个疑问了：`selectList`和`selectOne`都需要一个参数——`statementId`，
                 * 而此时我们是拿不到`statementId`的。
                 * 但是我们可以根据`method`对象得到方法名，和方法所在类的全类名。
                 * 因此我们需要规范下statementId的组成：
                 * **statementId  =  namespace.id  =  方法所在类的全类名.方法名
                 */
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className+"."+methodName;
                MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
                switch (mappedStatement.getSqlCommandType()) {
                    case "INSERT":
                        return insert(statementId,args);
                    case "UPDATE":
                        return update(statementId,args);
                    case "DELETE":
                        return delete(statementId,args);
                    case "SELECT":
                        //准备参数：2. args
                        //获取被调用方法的返回值类型
                        Type genericReturnType = method.getGenericReturnType();
                        //判断是否进行了泛型类型参数化 就是判断当前的返回值类型是否有泛型
                        if (genericReturnType instanceof ParameterizedType){
                            List<Object> selectList = selectList(statementId, args);
                            return selectList;
                        }
                        return selectOne(statementId,args);
                    default:
                        throw new Exception("Unknown execution method for: " + mappedStatement.getSqlCommandType());
                }



            }
        });
        return (T) o;
    }

    //获得将要执行方法的类型--SELECT、UPDATE、INSERT、DELETE

}
